package main

import (
	"encoding/json"
	"fmt"
	"math/rand"
	"os"
	"time"
)

func main(){
	name := []string{"怕怕怕","叶升韬","文笔","alalal","dhhed"}
	var name2 = make([]string,5)
	copy(name2,name)
	a:= IsFileExist1("a.txt")
	if a ==true{
		fmt.Println("文件以存在")
	}else{
		_, err := os.Create("a.txt")
		if err == nil{
			fmt.Println("文件创建成功")
		}
	}
	//num2 := make(map[string]int)
	//num2["i"] = 1
	//for _,v := range name{
	//	num2[v] = 0
	//}
	n := 5
	for{
		num2 := make(map[string]int)
		num2 = read()
		fmt.Println("经行抽同学请输入yes")
		var q string
		fmt.Scanln(&q)
		if q != "yes" {
			break
		}
		if len(name) == 0{
			fmt.Println("抽人游戏全员以全部抽到，抽人游戏重新开始")
			name = []string{"怕怕怕","叶升韬","文笔","alalal","dhhed"}
			fmt.Println(name)
			n = 5
		}else {
			fmt.Println("人数够,游戏继续")
			seednum := time.Now().UnixNano()
			rand.Seed(seednum)
			num := rand.Intn(n)
			n = n - 1
			fmt.Println("被抽到的同学是：",name[num])
			num2[name[num]] = num2[name[num]] + 1
			fmt.Println(name[num],"同学被抽到",num2[name[num]],"次")
			write(num2)
			name = append(name[:num],name[num+1:]...)
		}
	}
}

func read() map[string]int {
	// 读取文件
	userFile, err := os.ReadFile("a.txt")
	if err != nil {
		fmt.Println("Json文件读取错误:", err)
		return make(map[string]int)
	}
	// json->map
	var userInfo map[string]int
	err = json.Unmarshal([]byte(userFile), &userInfo)
	if userInfo== nil {
		fmt.Println("是空map")
		return make(map[string]int)
	}else {
		if err != nil{
			fmt.Println("json转换失败",err)
		}
	}
	return userInfo
}

func write(userinfo map[string]int){
	marshal,err := json.MarshalIndent(userinfo,"","")
	if err == nil{
		er := os.WriteFile("a.txt",marshal,0644)
		if er!=nil{
			fmt.Println("json写入错误",er)
		}
	}else {
		fmt.Println("map转换错误",err)
	}
}

func IsFileExist1(filename string) bool {
	if _,err:=os.Stat(filename);os.IsNotExist(err){
		return  false
	}
	return  true
}


